package com.zjw.nanyinge.controller;

import com.alibaba.fastjson.JSON;
import com.zjw.nanyinge.enums.MessageType;
import com.zjw.nanyinge.service.ChatService;
import com.zjw.nanyinge.utils.BeanUtils;
import com.zjw.nanyinge.utils.DomUtils;
import com.zjw.nanyinge.vo.req.MessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping("/weChat")
public class WeChatController {

    @Value("${weChat.check.token}")
    private String token;
    @Value("${weChat.check.encodingAESKey}")
    private String encodingAESKey;

    @GetMapping(value = "/checkToken", produces = "text/html;charset=utf-8")
    public String checkToken(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
        //排序
        String[] arr = {token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }
        log.info("WeChatController#checkToken，参数：{}", content);
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] data = digest.digest(content.toString().getBytes());
            String temp = byteToStr(data);
            if ((temp.toLowerCase()).equals(signature)) {
                return echostr;
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

    @PostMapping(value = "/checkToken")
    public String chat(HttpServletRequest request) throws IOException {
        MessageVO messageVO = parseMessage(request);
        log.info("WeChatController#chat，微信重试：参数messageVO：{}", JSON.toJSONString(messageVO));
        MessageType messageType = MessageType.valueOf(messageVO.getMsgType().toUpperCase());
        ChatService chatService = (ChatService) BeanUtils.getBean(messageType.getChatServiceClass());
        return chatService.chat(messageVO);
    }

    private MessageVO parseMessage(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        log.info("WeChatController#parseMessage原始参数xml:{}", sb);
        return DomUtils.getObject(sb.toString(), MessageVO.class);
    }
}
